<script setup>
import { ref, onMounted, watch } from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css' // 必须引入样式
import {
  adminUpdateInfoMdService,
  adminUpdatePotInfoMdService
} from '@/api/admin'
const vditorRef = ref(null)
const originalContent = ref('')
// 保存内容方法
const MdContent = defineModel('MdContent')
//分辨专家和意向专家(以下是管理员特有)
const userId = defineModel('userId')
const props = defineProps({
  type: String
})
const emit = defineEmits(['changeMdcontent'])
onMounted(() => {
  vditorRef.value = new Vditor('vditor-container', {
    height: '70vh', // 编辑器高度
    width: '100%', // 宽度自适应
    mode: 'ir', // 即时渲染模式
    toolbar: [
      // 自定义工具栏
      'emoji',
      'headings',
      'bold',
      'italic',
      '|',
      'link',
      {
        hotkey: '⌘M',
        icon: '<svg><use xlink:href="#vditor-icon-table"></use></svg>',
        tip: '表格',
        name: 'table2',
        tipPosition: 'n',
        prefix: '| col1',
        // suffix: ' | col2 | col3 |\n| --- | --- | --- |\n|  |  |  |\n|  |  |  |',
        click: () => {
          let rows = parseInt(prompt('请输入表格行数（不含表头）：', '2'))
          let cols = parseInt(prompt('请输入表格列数：', '3'))
          if (isNaN(rows) || rows < 1) {
            ElMessage.error('请输入大于0的行数')
            return
          }
          if (isNaN(cols) || cols < 1) {
            ElMessage.error('请输入大于0的列数')
            return
          }
          let prefix = '|'
          for (let i = 0; i < cols; i++) prefix += ` 列${i + 1} |`
          prefix += '\n|'
          for (let i = 0; i < cols; i++) prefix += ' --- |'
          let suffix = ''
          for (let i = 0; i < rows; i++) {
            suffix += '\n|'
            for (let j = 0; j < cols; j++) suffix += '  |'
          }
          vditorRef.value.insertValue(prefix + suffix)
        }
      },
      '|',
      'fullscreen',
      {
        name: 'save',
        tip: '保存',
        icon: '<svg t="1710000000000" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9000" width="32" height="32"><path d="M160 96c-35.2 0-64 28.8-64 64v704c0 35.2 28.8 64 64 64h704c35.2 0 64-28.8 64-64V224c0-17-6.7-33.3-18.7-45.3l-96-96A64 64 0 0 0 768 64H160z" fill="#fff" stroke="#111" stroke-width="64" p-id="9001"/><path d="M288 96h448v192a64 64 0 0 1-64 64H352a64 64 0 0 1-64-64V96z" fill="#fff" stroke="#111" stroke-width="64" p-id="9002"/><path d="M256 544a32 32 0 0 1 32-32h448a32 32 0 0 1 32 32v288a32 32 0 0 1-32 32H288a32 32 0 0 1-32-32V544z" fill="#fff" stroke="#111" stroke-width="64" p-id="9003"/><path d="M640 96v128" stroke="#111" stroke-width="64" stroke-linecap="round" fill="none" p-id="9004"/></svg>',
        click: () => handleSave()
      },
      'export'
    ],
    fullscreen: {
      index: 2000
    },
    cache: {
      enable: false // 禁用本地缓存
    },
    after: () => {
      vditorRef.value.setValue(`${MdContent.value}`)
      originalContent.value = vditorRef.value.getValue()
    }
  })
})
// 监听MdContent变化，更新编辑器内容（管理员多专家时改变）
watch(MdContent, (newVal) => {
  vditorRef.value.setValue(newVal)
  originalContent.value = vditorRef.value.getValue()
})

//检查是否保存
const handleSave = async () => {
  const content = vditorRef.value.getValue()
  if (content === originalContent.value) {
    ElMessage.info('内容没变化，不用保存')
    return
  }
  originalContent.value = content
  MdContent.value = content
  if (props.type === '0') {
    await adminUpdateInfoMdService(userId.value, content)
  } else if (props.type === '1') {
    await adminUpdatePotInfoMdService(userId.value, content)
  }
  //管理员页面的MD改动需要
  emit('changeMdcontent', true)
  ElMessage.success('MD保存成功')
}

// 检查是否有未保存的改动
const hasUnsavedChanges = () => {
  const content = vditorRef.value.getValue()
  if (content === originalContent.value) {
    return true
  }
  return false
}

// 暴露方法给父组件
defineExpose({
  hasUnsavedChanges
})
</script>
<template>
  <div class="md-editor-wrapper">
    <div id="vditor-container" class="vditor-custom-width"></div>
  </div>
</template>

<style scoped>
.md-editor-wrapper {
  width: 100vw;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.md-editor-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}
.vditor-custom-width {
  width: 100vw !important;
  margin: 0 !important;
  padding: 0 !important;
}
/* 重点：覆盖Vditor内容区宽度限制 */
:deep(.vditor-content),
:deep(.vditor-reset),
:deep(.vditor-ir),
:deep(.vditor-wysiwyg),
:deep(.vditor-textarea) {
  max-width: 100vw !important;
  width: 100vw !important;
  margin: 0 !important;
  padding: 0 20px !important;
  box-sizing: border-box;
}
.vditor--fullscreen {
  left: -41px !important;
  width: calc(100vw + 41px) !important;
}
</style>
